#include "common.h"

Conn * CONN_Get_Connection(int sock)
{
    int         instance;
    Event       *rev, *wev;
    Conn  *c;
    off_t index;

    c = g_server->free_connections;

    if (c == NULL) {
 	    Log_Write(g_server->log, "CONN: no conns");
        return NULL;
    }

    g_server->free_connections = c->data;
    g_server->free_connection_n--;

    rev = c->read;
    wev = c->write;
    index = c->index;
    memset(c, 0, sizeof(Conn));

    c->read = rev;
    c->write = wev;
    c->index = index;
    c->fd = sock;

    instance = rev->instance;

    memset(rev, 0, sizeof(Event));
    memset(wev, 0, sizeof(Event));

    rev->instance = !instance;
    wev->instance = !instance;

    rev->data = c;
    wev->data = c;

    wev->write = 1;

    return c;
}

void CONN_Free_Connection(Conn *c)
{
    c->data = g_server->free_connections;
    g_server->free_connections = c;
    g_server->free_connection_n++;
}

static int count = 0;

void CONN_Close_Connection(Conn *c)
{
    int  fd;

    if (c->fd == -1) {
	    Log_Write(g_server->log, "CONN: close the closed fd");
        return;
    } 

    /* here we only set the event->active = 0 to disable the IO event */
    c->read->closed = 1;
    c->write->closed = 1;
    c->read->active = 0;
    c->write->active = 0;

    CONN_Free_Connection(c);
    fd = c->fd;
    c->fd = -1;

    close(fd);
}


